package com.sc.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.sc.gateway.dto.ResultDTO;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Component
public class RequestFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().get("Authorization").get(0);
        System.out.println("请求拦截___________");
        System.out.println(exchange.getRequest().getPath());
        if(exchange.getRequest().getPath().toString().indexOf("login")>-1 || exchange.getRequest().getPath().toString().indexOf("logout")>-1){
            return chain.filter(exchange);
        }else{
            // token 不存在返回401
            if (StringUtils.isBlank(token)) {
                ServerHttpResponse response = exchange.getResponse();
                ResultDTO r =  new ResultDTO(401,"token不存在",null);
                byte[] bits = JSON.toJSON(r).toString().getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = response.bufferFactory().wrap(bits);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //指定编码，否则在浏览器中会中文乱码
                response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            }
            // 传入token 和url 记录接口调用情况
            Map map = new HashMap();
            map.put("token",token);
            map.put("url",exchange.getRequest().getPath().toString());
            String message = JSON.toJSONString(map);
            redisTemplate.convertAndSend("sys-log",message);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -100;
    }

}


